window.addEventListener('load', (event) => {
    let tblEl=document.querySelector(".mime-grid");
    // 默认加载一次
    main(9,9)
    const primaryBtn = document.getElementById('primaryBtn');
    const intermediateBtn = document.getElementById('intermediateBtn');
    const seniorBtn = document.getElementById('seniorBtn');
    const restart = document.getElementById('restart');
    // 记录当前模式
    let mode = 9;
    // 点击初级事件
    primaryBtn.onclick = function () {
        clearDom()
        main(9,9)
        mode = 9
        restarttime(game)
    }
    // 点击中级事件
    intermediateBtn.onclick = function () {
        clearDom()
        main(16,16)
        mode = 16
        restarttime(game)
    }
    // 点击高级事件
    seniorBtn.onclick = function () {
        clearDom()
        main(32,32)
        mode = 32
        restarttime(game)
    }
    // 点击重新开始事件
    restart.onclick = function () {        
        clearDom()
        main(mode,mode)
        // 重置时间
        restarttime(game)
    }   
    // 清除旧的dom元素
    function clearDom(){
        while (tblEl.firstChild) {
            tblEl.removeChild(tblEl.firstChild);
        }
    }
});

function restarttime(game){
        game.elapsed = 0
        refreshTimer(game)
        // 如果有正在运行的计时器,需要先清除
        console.log(game);
        
        if(regularTime) {
            clearInterval(regularTime)
        }
        game.state = 0 // 重置状态为准备开始
        // 重置剩余雷数
        game.remainingMines = game.numofMines;
        updateMinesCount(game);
}

function randomMime(game){ //随机产生雷
    let{nRows,nCols}=game;
    let mines=[]
    let existed={}
    for(let i =0; i<game.numofMines;i++){
        while(true){
            let  rowIdx=Math.floor(Math.random()*nRows);
            let  colIdx=Math.floor(Math.random()*nCols);
            let key =`${rowIdx},${colIdx}`;
            if (key in existed){
                continue;
            }
       
            mines.push([rowIdx,colIdx]);
            existed[key]=true;
            break;

        }
        
    }
    game. mines=mines;
}

function handleClick(game,rowIdx,colIdx){
    if(game.state==0){
        game.state=1;
        startingGame(game);
    }
    if(game.state==2||game.state==3){
        return;
    }

    let{nRows,nCols,cells}=game;
    let cell= cells[rowIdx][colIdx];

    if (cell.flag){
        return;
    }
    // showAllMines(game);
    console.log(cell);
    
    if(cell.value==-1){    
        cell.el.classList.add('exploded');
        // 游戏失败时显示所有地雷
        showAllMines(game);
        loseGame(game);
    }else if(cell.value>0){
        cell.open=true;
        cell.el.classList.add('open');
        checkWin(game); // 每次打开格子后检查是否胜利
    }else if(cell.value==0){
        clearSafeArea(game,rowIdx,colIdx);
        checkWin(game); // 清除安全区域后检查是否胜利
        console.log("标记");
        
    }
}

// 添加显示所有地雷的函数
function showAllMines(game) {
    let{nRows,nCols,cells}=game;
    for(let rowIdx=0; rowIdx<nRows; rowIdx++){
        for(let colIdx=0; colIdx<nCols; colIdx++){
            let cell = cells[rowIdx][colIdx];
            if(cell.value == -1){
                cell.el.classList.add('exploded');
            }
        }
    }
}


function checkWin(game) {
    let { nRows, nCols, cells } = game;
    let unopenedCount = 0;
    let unmarkedMinesCount = 0;

    for (let rowIdx = 0; rowIdx < nRows; rowIdx++) {
        for (let colIdx = 0; colIdx < nCols; colIdx++) {
            let cell = cells[rowIdx][colIdx];
            // 如果一个非地雷格子没有打开，游戏还没有胜利
            if (!cell.open && cell.value != -1) {
                unopenedCount++;
            }
            // 如果地雷没有被标记，计数增加
            if (cell.value === -1 && !cell.flag) {
                unmarkedMinesCount++;
            }
        }
    }
    console.log(unmarkedMinesCount,"chuli");
    
    // 当所有非地雷格子都被打开，或所有地雷都被标记时，游戏胜利
    if (unopenedCount === 0 || unmarkedMinesCount === 0) {
        winGame(game);
    }
}

function winGame(game){
    game.state = 2;
    clearInterval(regularTime);
    
    // 自动标记所有未标记的地雷
    let{nRows,nCols,cells}=game;
    for(let rowIdx=0; rowIdx<nRows; rowIdx++){
        for(let colIdx=0; colIdx<nCols; colIdx++){
            let cell = cells[rowIdx][colIdx];
            if(cell.value == -1 && !cell.flag){
                cell.flag = true;
                cell.el.classList.add('flag');
            }
        }
    }
    
    // 计算得分（可以根据时间和难度来计算）
    let score = Math.floor(( game.elapsed) * (game.nRows/9));
    
    // 显示胜利信息
    setTimeout(() => {
        alert(`恭喜你赢了！\n用时：${game.elapsed}秒\n得分：${score}分`);
    }, 100);
}

function loseGame(game){
    game.state = 3;
    clearInterval(regularTime);
    
        setTimeout(() => {
            alert(`游戏失败！\n已用时：${game.elapsed}秒`);
        }, 100);
    }
// 在外部创建一个定时器
let regularTime = null
function startingGame(game){
    game.state=1;
    regularTime=setInterval(()=>{
        game.elapsed=game.elapsed+1;
        
        refreshTimer(game);
    },1000);
}
function refreshTimer(game){
    let el=document.querySelector(".game-info>.timer");
    let minutes = Math.floor(game.elapsed / 60);
    let seconds = game.elapsed % 60;
    // 格式化显示，确保分钟和秒都是两位数
    el.innerText = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
function clearSafeArea(game,rowIdx,colIdx) {
    let{nRows,nCols,cells}=game;
    let cell=cells[rowIdx][colIdx]
    if(cell.value!=0){
       return;
    }
    cell.open=true;
    cell.el.classList.add("open");
    for (let [deltaRow,deltaCol] of directions){ 
        let newRow=rowIdx+deltaRow;
        let newCol=colIdx+deltaCol;
        if(newRow<0||newRow>=nRows){
            continue;
        }
        if(newCol<0||newCol>=nCols){
            continue;
        }
        console.log("clear:",newRow.newCol,nCols);
        let neighborcell= cells[newRow][newCol ];
        if(neighborcell.open || neighborcell.flag){
            continue;
        }
        
        if (neighborcell.value>0){
            neighborcell.open=true;
            neighborcell.el.classList.add('open');
            continue;
        } 
        if (neighborcell.value==0){
         
            clearSafeArea(game,newRow,newCol);
        }
       
    }   
}

// 修改 handleflagcell 函数，更新剩余地雷计数
// function handleflagcell(game, rowIdx, colIdx) {
//     let { nRows, nCols, cells } = game;
//     if (game.state == 0) {
//         startingGame(game);
//     }
//     if (game.state == 2 || game.state == 3) {
//         return;
//     }

//     let cell = cells[rowIdx][colIdx];
//     if (cell.open) {
//         return;
//     }
//     if (cell.flag) {
//         cell.flag = false;
//         cell.el.classList.remove('flag');
//         game.remainingMines++; // 取消标记时增加剩余雷数
//         updateMinesCount(game);
//     } else {
//         if (game.remainingMines > 0) {
//             cell.flag = true;
//             cell.el.classList.add('flag');
//             game.remainingMines--;
//             updateMinesCount(game);
//         }
//     }
// }
function handleflagcell(game, rowIdx, colIdx) {

    let { nRows, nCols, cells } = game;
    if (game.state == 0) {
        startingGame(game);
    }
    if (game.state == 2 || game.state == 3) {
        return;
    }

    let cell = cells[rowIdx][colIdx];
    if (cell.open) {
        return;
    }
    console.log(cell,"标记右键");
    if (cell.flag) {
        cell.flag = false;
        cell.el.classList.remove('flag');
        game.remainingMines++; // 取消标记时增加剩余雷数
        updateMinesCount(game);
    } else {
        if (game.remainingMines > 0) {
            cell.flag = true;
            cell.el.classList.add('flag');
            game.remainingMines--;
            updateMinesCount(game);
        }
    }
    // 检查是否所有地雷都被标记
    checkWin(game);
}

function handlenumber(game,rowIdx,colIdx){
    let{nRows,nCols,cells}=game;
    let cell=cells[rowIdx][colIdx];
    for (let [deltaRow,deltaCol] of directions){ 
        let newRow=rowIdx+deltaRow;
        let newCol=colIdx+deltaCol;
        if(newRow<0||newRow>=nRows){
            continue;
        }
        if(newCol<0||newCol>=nCols){
            continue;
        }
        let neighborcell= cells[newRow][newCol ];
        if(neighborcell.open || neighborcell.flag){
            continue;
        }
        if (neighborcell.value>=0){
            neighborcell.open=true;
            neighborcell.el.classList.add('open');
            continue;
        } 
        if (neighborcell.value==-1){
            neighborcell.open=true;
            neighborcell.el.classList.add('exploded');
            loseGame(game)
            showAllMines(game)
        }
    }
}


function countSurroundingMines(game){
    let{nRows,nCols,cells}=game;
    for (let rowIdx=0;rowIdx<nRows;rowIdx++){
        for (let colIdx=0;colIdx<nCols;colIdx++){
            let cell= cells[rowIdx][colIdx];
            if(cell.value==-1){
                continue;
            }
            let numMines=0;
            for (let [deltaRow,deltaCol] of directions){ 
                let newRow=rowIdx+deltaRow;
                let newCol=colIdx+deltaCol;
                if(newRow<0||newRow>=nRows){
                    continue;
                }
                if(newCol<0||newCol>=nCols){
                    continue;
                }
                let neighborcell= cells[newRow][newCol ];
                if(neighborcell.value==-1){
                    numMines ++;
                }
        }
        cell.value=numMines;
        if(numMines==1){
            cell.el.classList.add("warn-1");
        }else if (numMines==2){
            cell.el.classList.add("warn-2");
        }else if (numMines==3){
            cell.el.classList.add("warn-3");
        }else if (numMines==4){
            cell.el.classList.add("warn-4");
        }else if (numMines==5){
            cell.el.classList.add("warn-5");
        }else if (numMines==6){
            cell.el.classList.add("warn-6");
        }else if (numMines==7){
            cell.el.classList.add("warn-7");
        }else if (numMines==8){
            cell.el.classList.add("warn-8");
        }else if (numMines==0){
            cell.el.classList.add("warn-0");
        }

        if(numMines>0){
            //cell.el.innerHTML=numMines;
            let mineEl=cell.el.querySelector('.mine');
            mineEl.innerHTML=numMines;

        }
    }
    }
}

let game = null



function main(nRowsVal,nColsVal){
    game={
        nRows: nRowsVal,
        nCols: nColsVal,
        // 根据不同难度设置不同的雷数
        numofMines: nRowsVal === 9 ? 5 : (nRowsVal === 16 ? 40 : 99),
        elapsed:0,
        timeLimit: 300,
        remainingMines: nRowsVal === 9 ? 5 : (nRowsVal === 16 ? 40 : 99),
        state:0,
        drawGrid:function(){//线板
            let tblEl=document.querySelector("#gameboard > table.mime-grid");
            let cells=[] ; 
            for(let rowIdx=0; rowIdx <this.nRows;rowIdx++){
                let trEl=document.createElement("tr"); 
                let cellRow=[];
                    for(let colIdx=0; colIdx <this.nCols;colIdx++){
                    let tdEl=document.createElement("td"); 
                    let cellDiv=document.createElement("div");
                    cellDiv.className='cell';
        
                    cellDiv.innerHTML=`<div class='mine'></div><div class='flag'>&#x1F6A9;</div>`
        
                    cellDiv.addEventListener("click",(e)=>{ 
                        handleClick(game,rowIdx,colIdx)
                    })
                    cellDiv.addEventListener('contextmenu',(e)=>{
                        e.preventDefault()
                        handleflagcell(game,rowIdx,colIdx)
                        
                        
                    })
                    cellDiv.addEventListener("dblclick",(e)=>{ 
                        handlenumber(game,rowIdx,colIdx)
                    })
                    tdEl.append(cellDiv); 
                    trEl.append(tdEl);
                   
        
                    cellRow.push({
                        open:false,
                        el:cellDiv,
                    })
                }
                cells.push(cellRow);
                tblEl.append(trEl); 
            }
            
            //绘制雷
            for(let mine of this.mines){
                let [rowIdx,colIdx] = mine;
                let cell= cells[rowIdx][colIdx];
                cell.value=-1,//有雷设置-1，没有雷此值表示周边雷数
                mineEl = cell.el.querySelector(".mine");
                mineEl.innerHTML="&#128163;";
                //cell.el.classList.add('warn-0')
            }  
            this.cells=cells;
        }
    };
 
    randomMime(game);
    game.drawGrid()

    countSurroundingMines(game);
    updateMinesCount(game);
}

function showRemainNum(game){
    let remainingDiv=document.querySelector(".game-info>.remaining");
    remainingDiv.innerHTML=game.remainingNum;


}
let directions=[
    [-1,-1],
    [-1,0],
    [-1,1],
    [0,-1],
    [0,1],
    [1,-1],
    [1,0],
    [1,1],
]


// 添加更新剩余雷数显示的函数
function updateMinesCount(game) {
    let minesCountEl = document.querySelector(".game-info>.remaining");
    if(minesCountEl) {
        minesCountEl.innerText = game.remainingMines;
    }
}